package com.example.servlet;

import cn.hutool.json.JSONUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "login-servlet", value = "/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req,
                          HttpServletResponse resp)
            throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 响应的是JSON格式的字符串
        // resp.setCharacterEncoding("UTF-8");
        // 响应的JSON格式的字符串，并且前端收到后会自动解析成对象结构
        resp.setContentType("application/json; charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Map<String, Object> result = new HashMap<>();
        result.put("status", false);
        PrintWriter writer = resp.getWriter();
        if (username == null || username.trim().isEmpty()
                || password == null || password.trim().isEmpty()) {
            result.put("message", "未填写用户名或密码");
            writer.write(JSONUtil.toJsonStr(result));
            writer.flush();
            writer.close();
            return;
        }
        if (username.equals("admin") && password.equals("123456")) {
            result.put("status", true);
            HttpSession session = req.getSession();
            session.setAttribute("token", username);
            session.setMaxInactiveInterval(60 * 5);
        } else {
            result.put("message", "用户名或密码错误");
        }
        writer.write(JSONUtil.toJsonStr(result));
        writer.flush();
        writer.close();
    }
}
